package daos;

import entitys.Campeonato;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import utils.JpaUtils;

/**
 *
 * @author Amauri
 */
public class CampeonatoDAO {
    
    public CampeonatoDAO(){}
    
    public void persistir(Campeonato camp){
    
        if (camp.getID() == null){
            this.insert(camp);
        }else{
            this.update(camp);
        }
    }
    
    public void insert(Campeonato camp) {
        EntityManager manager = JpaUtils.getEntityManager();
        try {
            manager.getTransaction().begin();
            manager.persist(camp);
            manager.getTransaction().commit();
        } catch (Exception e) {
            manager.getTransaction().rollback();
        } finally {
            manager.close();
            JpaUtils.close();
        }
    }
    public void update(Campeonato camp) {
        EntityManager manager = JpaUtils.getEntityManager();
        try {
            manager.getTransaction().begin();
            manager.merge(camp);
            manager.getTransaction().commit();
        } catch (Exception e) {
            manager.getTransaction().rollback();
        } finally {
            manager.close();
            JpaUtils.close();
        }
    }
            
    public void delete(Campeonato camp) {
        EntityManager manager = JpaUtils.getEntityManager();
        try {
            manager.getTransaction().begin();
            camp = manager.merge(camp);
            manager.remove(camp);
            manager.getTransaction().commit();
        } catch (Exception e) {
            manager.getTransaction().rollback();
        } finally {
            manager.close();
            JpaUtils.close();
        }
    }
    
    public Campeonato findById(Long id) {
        EntityManager manager = JpaUtils.getEntityManager();
        try {
            return manager.find(Campeonato.class, id);
        } finally {
            manager.close();
            JpaUtils.close();
        }
    }
    
    public List<Campeonato> listAll() {
        EntityManager manager = JpaUtils.getEntityManager();
        try {
            Query query = manager.createQuery("select c from Campeonato c", Campeonato.class);
            return query.getResultList();
        } finally {
            manager.close();
            JpaUtils.close();
        }
    }
    
}
